const express = require("express");
const router = express.Router();
const Dev = require("../../models/Dev");

function getReqDevNames(arr) {
  let dev_names = new Array();
  arr.forEach(item => {
    if (dev_names.indexOf(item["设备名称"]) == -1) {
      dev_names.push(item["设备名称"]);
    }
  });
  return dev_names;
}

function getUnfindDevs(req_arr, get_arr) {
  return req_arr.filter(r_item => {
    return !get_arr.some(g_item => {
      return r_item["设备名称"] == g_item["dev_name"];
    });
  });
}

router.get("/devs", async (req, res) => {
  let model = await Dev.find();
  res.send(model);
});

router.post("/devs", async (req, res) => {
  try {
    let { devs, hospitel_id } = req.body;
    let names = getReqDevNames(devs);
    let find_datas = await Dev.find({
      dev_name: { $in: names },
      hospitel_id: hospitel_id
    });
    let unfindDevs = getUnfindDevs(devs, find_datas),
      insert_num = unfindDevs.length,
      uninsert_num = devs.length - insert_num;
    let models = await Dev.insertMany(unfindDevs);
    if (models.length > 0) {
      res.send({
        type: "success",
        message: `共${devs.length}台设备,导入设备数据${insert_num}台，重复数据 ${uninsert_num}台。`
      });
    } else {
      res.send({
        type: "warning",
        message: `共${devs.length}台设备,导入设备数据${insert_num}台，重复数据 ${uninsert_num}台。`
      });
    }
  } catch (e) {
    res.send({ type: "error", message: "请检查导入表是否正确" });
  }
});

router.put("/devs", async (req, res) => {
  try {
    let { devs, hospitel_id } = req.body;
    let names = getReqDevNames(devs);
    let find_datas = await Dev.find({
      dev_name: { $in: names },
      hospitel_id: hospitel_id
    });
    find_datas.forEach(f_item => {
      let field = ["68码", "是否计量", "风险等级", "折旧年限(年)"]
      devs.forEach(d_item => {
        if (f_item["设备名称"] == d_item["设备名称"]) {
          field.forEach(item => {
            f_item[item] = d_item[item];
          })
        }
      })
    })
    let models = find_datas.save();
    if (models.length > 0) {
      res.send({
        type: "success",
        message: `覆盖导入设备数据共${find_datas.length}台。`
      });
    }
  } catch (e) {
    res.send({ type: "error", message: "请检查导入表是否正确" });
  }
})

router.post("/devs/fetch", async (req, res) => {
  let { table_json, hospitel_id } = req.body;
  let names = getReqDevNames(table_json)
  let find_devs = await Dev.find({
    dev_name: { $in: names },
    hospitel_id: hospitel_id
  });
  table_json.forEach(r_item => {
    let field = ["设备名称", "68码", "是否计量", "风险等级", "折旧年限(年)"]
    let dev = find_devs.find(d_item => {
      return d_item[field[0]] == r_item[field[0]];
    })
    if (dev) {
      field.forEach(item => {
        r_item[item] = dev[item];
      });
    }
  })
  res.send(table_json);
});

router.delete("/devs/:id", async (req, res) => {
  let model = await Dev.findByIdAndRemove(req.params.id);
  res.send(model);
});

module.exports = router;
